<template>
    <div class="app-container">
        <!-- 第一部分：页面标题与介绍 -->
        <div class="page-header" style="margin-top: 0px">
            <h3 class="page-title">ADE Knowledge Search</h3>
            <p class="page-description">
                Retrieve ADE (Adverse Drug Event) case knowledge related to the inputted progress notes from the ADE
                knowledge base based on text similarity.
            </p>
        </div>

        <!-- 第二部分：信息输入部分 -->
        <el-card class="box-card">
            <template #header>
                <div class="clearfix">
                    <span>Input Parameters</span>
                </div>
            </template>

            <el-form :inline="true" class="demo-form-inline" ref="queryform" :model="form" :rules="rules">
                <!--选择 ADE 库-->
                <el-form-item label="ADE KB" prop="adekb">
                    <el-select v-model="form.adekb" placeholder="Select ADE KB" size="mini" clearable
                        style="width:150px">
                        <el-option v-for="dict in adekbs" :key="dict.id" :label="dict.name" :value="dict.id" />
                    </el-select>
                </el-form-item>

                <!--选择切分方式-->
                <el-form-item label="Chunk Type" prop="chunkType">
                    <el-select v-model="form.chunkType" placeholder="Select Chunk Type" size="mini" clearable
                        style="width:150px">
                        <el-option v-for="dict in dict.type.chunk_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>

                <!--选择embed模型-->
                <el-form-item label="Embed Model" prop="embedModel">
                    <el-select v-model="form.embedModel" placeholder="Select Embedding Model" size="mini" clearable>
                        <el-option v-for="dict in dict.type.embed_models" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>

                <!--选择相似度阀值-->
                <el-form-item label="Sim Score" prop="simScore">
                    <el-input-number v-model="form.simScore" placeholder="Similarity Score" style="width:100px" />
                </el-form-item>

                <!--选择topN-->
                <el-form-item label="TopN" prop="topN">
                    <el-input-number v-model="form.topN" placeholder="Top N" :min="1" :max="100" style="width:100px" />
                </el-form-item>

                <!--是否启用调试模式-->
                <el-form-item>
                    <el-checkbox v-model="form.debug">Debug Mode</el-checkbox>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" size="mini" icon="el-icon-refresh" @click="randomEmr"
                        :loading="nexting">Random
                        Case</el-button>
                    <el-button type="success" size="mini" icon="el-icon-search" @click="searchAde"
                        :loading="loading">Search</el-button>

                </el-form-item>
            </el-form>


            <!--病程记录内容-->
            <el-form ref="emrform" :model="form" :rules="rules">

                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="Medical Record" prop="emr">
                            <el-button type="text" size="mini" icon="el-icon-view" @click="handleStandardDetail"
                                title="detail" />
                            <el-input type="textarea" :rows="5" v-model="form.emr"
                                placeholder="Please input medical record content..."></el-input>
                        </el-form-item>

                    </el-col>
                    <!--
                    <el-col :span="12">
                        <el-form-item label="ADEs" prop="ades">
                            <pre class="json-result">{{ jsonText }}</pre>
                        </el-form-item>
                    </el-col>
                    -->
                </el-row>
            </el-form>

        </el-card>


        <!--第三部分 展示结果-->
        <el-card class="box-card" v-loading="loading">
            <template #header>
                <div class="clearfix" style="text-align: center; font-weight: 600">
                    <span>ADE Search Result</span>
                </div>
            </template>

            <el-row :gutter="20" style="margin-top: 20px" v-if="form.debug">
                <!--展示分割结果-->
                <el-col :span="24">
                    <el-card class="result-card">
                        <!--
                        <div slot="header" class="clearfix">
                            <span>Chunk Result</span>
                            <el-button style="float: right; padding: 3px 0" type="text">
                                <el-tooltip
                                    content="Segmentation results of electronic medical record content based on selected segmentation methods"
                                    placement="top">
                                    <i class="el-icon-question"></i>
                                </el-tooltip>
                            </el-button>
                        </div>
                        -->
                        <div class="compact-table-container">
                            <el-table :data="flattenData" border :span-method="objectSpanMethod" size="mini"
                                :header-cell-style="{ padding: '0px 0' }" :cell-style="{ padding: '0px 0' }"
                                style="width: 100%; padding: 0;margin: 0;">
                                <el-table-column type="index" label="NO" width="60" align="center" />
                                <el-table-column label="Chunk" prop="chunk" align="left" show-overflow-tooltip />
                                <el-table-column label="SimScore" prop="simScore" align="center" />
                                <el-table-column label="Text" prop="text" align="left" show-overflow-tooltip />
                                <el-table-column label="Ade" prop="ade" align="left" show-overflow-tooltip />
                                <el-table-column label="Explains" prop="explain" align="left" show-overflow-tooltip />
                            </el-table>
                        </div>
                    </el-card>
                </el-col>
            </el-row>

            <el-row :gutter="20" style="margin-top: 20px" v-if="!form.debug">
                <!--展示分割结果-->
                <el-col :span="24">
                    <el-card class="result-card">
                        <div class="compact-table-container">
                            <el-table :data="ades" border size="mini" :header-cell-style="{ padding: '0px 0' }"
                                :cell-style="{ padding: '0px 0' }" style="width: 100%; padding: 0;margin: 0;">
                                <el-table-column type="index" label="NO" width="60" align="center" />
                                <el-table-column label="SimScore" prop="simScore" align="center" />
                                <el-table-column label="Text" prop="text" align="left" show-overflow-tooltip />
                                <el-table-column label="Ade" prop="ade" align="left" show-overflow-tooltip />
                                <el-table-column label="Explains" prop="explain" align="left" show-overflow-tooltip />
                            </el-table>
                        </div>
                    </el-card>
                </el-col>
            </el-row>

        </el-card>

        <el-dialog :visible.sync="showDialog"  width="80%" :title="'Standard Detail'">
            <standard-detail-dialog v-if="selectedId" :id="selectedId" />
        </el-dialog>

    </div>

</template>

<script>
import { listAllAdebase, search } from "@/api/ade/adebase";
import { randomStandard } from "@/api/ade/standard";
import StandardDetailDialog from "@/views/ade/standard/detail.vue";

export default {
    name: "AdeBaseSearch",
    dicts: [
        "chunk_type",
        "embed_models",
    ],
    components: {
        StandardDetailDialog,
    },
    data() {
        return {
            form: {
                adekb: null,    //ADE知识库
                embedModel: 'shaw/dmeta-embedding-zh:latest', //嵌入模型
                chunkType: 'mark',  //切分方式
                simScore: 0.7,   //相似度阈值
                topN: 5,  //返回结果数量
                emr: "", //病程记录内容
                debug: true //是否启用ADE过滤
            },
            adekbs: [], //ADE知识库列表
            loading: false, //加载状态
            nexting: false, //随机案例加载状态
            rules: {
                adekb: [
                    { required: true, message: "Please select an ADE knowledge base", trigger: "change" }
                ],
                embedModel: [
                    { required: true, message: "Please select an embedding model", trigger: "change" }
                ],
                chunkType: [
                    { required: true, message: "Please select a chunk type", trigger: "change" }
                ],
                simScore: [
                    { type: 'number', min: 0, max: 1, message: "Similarity score must be between 0 and 1", trigger: "blur" }
                ],
                emr: [
                    { required: true, message: "Please input medical record content", trigger: "blur" }
                ],
            },
            ades: [], // 存储ADE与药物的配对结果
            rawData: [], // 用于存储ADE与药物的配对结果
            spanArr: [], // 存储合并规则
            flattenData: [], // 扁平化后的数据

            //Standard 详情对话框参数
            showDialog: false,
            selectedId: null,

        };
    },
    created() {
        // 初始化时加载ADE知识库列表
        this.listallAdebases();
    },
    methods: {
        //打开标准数据集详情页面
        handleStandardDetail() {
            console.log("Opening standard detail for ID:", this.selectedId);
            this.showDialog = true;
        },
        listallAdebases() {
            var data = { status: '' };
            // Fetch all ADE knowledge bases
            listAllAdebase(data).then(response => {
                this.adekbs = response.data;
                if (this.adekbs.length > 0) {
                    this.form.adekb = this.adekbs[0].id; // 默认选择第一个ADE知识库
                }
            }).catch(error => {
                this.$message.error("Failed to load ADE knowledge bases: " + error.message);
            });
        },
        // 随机病例
        randomEmr() {
            this.nexting = true;
            var data = { status: "", source: "" };
              //初始化
            this.ades = [];
            this.rawData = [];
            this.flattenData = [];
            this.spanArr = [];
            randomStandard(data)
                .then((response) => {
                    if (response.data == null || response.data == undefined) {
                        this.$message.warning(
                            "No aviliable emr data, please change the source or status!"
                        );
                        this.nexting = false;
                        return;
                    }
                    this.selectedId = response.data.id;   //当前标准数据集ID
                    this.form.emr = response.data.content;
                    this.nexting = false;
                })
                .catch((error) => {
                    console.error("Error fetching random EMR:", error);
                    this.$message.error("Too fast, please wait a moment!");
                    this.nexting = false;
                });
        },
        searchAde() {
            //初始化
            this.ades = [];
            this.rawData = [];
            this.flattenData = [];
            this.spanArr = [];
            console.log("Searching ADE with parameters:", this.form);
            this.$refs.queryform.validate((valid) => {
                if (valid) {
                    this.loading = true;
                    this.nexting = true;
                    // 调用API进行ADE知识检索
                    search(this.form).then(response => {
                        console.log("Search response:", response);
                        this.rawData = response.data.pairs || [];
                        response.data.ades.forEach(item => {
                            this.ades.push({
                                simScore: item.simScore,
                                text: item.knowledge.text,
                                ade: item.knowledge.ade,
                                explain: item.knowledge.explain
                            });
                        });
                        this.processData(); // 处理数据
                        this.loading = false;
                        this.nexting = false;
                    }).catch(error => {
                        this.$message.error("Search failed: " + error.message);
                        this.loading = false;
                        this.nexting = false;
                    });
                } else {
                    console.log("Validation failed");
                }
            });
        },
        processData() {
            let pos = 0;
            this.rawData.forEach(item => {

                // 如果 results 为空，生成一个空对象占位
                const results = item.ades.length > 0
                    ? item.ades
                    : [{ simScore: "", knowledge: { text: "", ade: "", explain: "" } }];

                // 记录需要合并的行数
                this.spanArr.push(results.length);

                // 扁平化数据
                results.forEach(result => {
                    this.flattenData.push({
                        chunk: item.chunk,
                        simScore: result.simScore,
                        text: result.knowledge.text,
                        ade: result.knowledge.ade,
                        explain: result.knowledge.explain
                    });
                });
            });
            // 计算合并规则（类似 Excel 合并单元格的 [rowspan, colspan]）
            this.spanArr = this.getSpanArr(this.spanArr);
        },
        // 计算合并规则
        getSpanArr(data) {
            const arr = [];
            data.forEach(num => {
                // 每个 content 至少合并 1 行
                const rowspan = Math.max(num, 1);
                arr.push(rowspan);
                // 如果需要合并多行，补充 0 表示后续行被合并
                for (let i = 1; i < rowspan; i++) {
                    arr.push(0);
                }
            });
            return arr;
        },
        // 单元格合并方法
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            // 只在 content 列合并（第一列）
            if (columnIndex === 1) {
                const rowspan = this.spanArr[rowIndex];
                const colspan = rowspan > 0 ? 1 : 0;
                return {
                    rowspan: rowspan,
                    colspan: colspan
                };
            }
        }
    }
};

</script>

<style scoped>
.box-card {
    margin-bottom: 10px;
}

.page-header {
    margin-bottom: 20px;
}

.page-title {
    margin-top: 5px;
    font-size: 22px;
    color: #303133;
    margin-bottom: 0px;
    font-weight: bold;
}

.page-description {
    font-size: 16px;
    color: #606266;
    line-height: 1.5;
}

.result-card {
    height: 100%;
}

.annotated-text {
    min-height: 120px;
    font-size: 13px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 4px;
    line-height: 1.4;
}

.ade-term {
    background-color: #ffcccc;
    padding: 0 3px;
    border-radius: 2px;
}

.drug-term {
    background-color: #ccffcc;
    padding: 0 3px;
    border-radius: 2px;
}


/* 容器样式：消除默认边距 */
.compact-table-container {
    padding: 0;
    margin: 0;
}

/* 表格整体样式 */
.compact-table-container ::v-deep .el-table {
    font-size: 12px;
    /* 更小的字体 */
}

/* 表头样式 */
.compact-table-container ::v-deep .el-table th {
    background-color: #f5f7fa;
    font-weight: 500;
    color: #333;
}

/* 单元格样式 */
.compact-table-container ::v-deep .el-table td {
    border-right: 1px solid #ebeef5;
    /* 更细的边框 */
}

/* 斑马纹颜色调整 */
.compact-table-container ::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td {
    background-color: #fafafa;
}

/* 悬停效果 */
.compact-table-container ::v-deep .el-table--enable-row-hover .el-table__body tr:hover>td {
    background-color: #f0f7ff;
}

/* 滚动条优化（可选） */
.compact-table-container ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    height: 6px;
}

.compact-table-container ::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}
</style>